<?php

namespace plugin\ycMassage\app\api\controller;

use app\common\manager\SettingsMgr;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageCollectService;
use plugin\ycMassage\app\model\MassageCollectTechnician;
use plugin\ycMassage\app\model\MassageCoupon;
use plugin\ycMassage\app\model\MassageCouponCode;
use plugin\ycMassage\app\model\MassageOrdersSub;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\app\model\MassageUserWallet;
use plugin\ycMassage\app\model\MassageUserWechat;
use plugin\ycMassage\utils\enum\CouponCodeState;
use plugin\ycMassage\utils\enum\OrdersState;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\facade\Cache;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;
use GuzzleHttp\Client;
use plugin\ycMassage\utils\Rsa;
use plugin\ycMassage\utils\WechatHelper;
use think\facade\Env;
use think\Response;

class UserController extends BaseController
{
    public function info(Request $request)
    {
        try {
            $data = MassageUser::getInfo($request->uid);
            return $this->successRes($data);
        } catch (\Throwable $th) {
            return $this->failFul($th->getMessage(), $th->getCode());
        }
    }
    public function save(Request $request)
    {
        $nickname = $request->post('nickname');
        $headimg = $request->post('headimg');
        $birthday = $request->post('birthday');
        $gender = $request->post('gender');
        $uid = $request->uid;
        $saas_appid = $request->saas_appid;
        $model = MassageUser::where(['saas_appid' => $saas_appid, 'id' => $uid])->find();
        if (!$model) {
            return $this->fail('用户不存在');
        }
        if ($nickname) {
            $model->nickname = $nickname;
        }
        if ($headimg) {
            # 如若headimg中包含https://thirdwx.qlogo.cn则不替换
            if (!Str::contains($headimg, 'https://thirdwx.qlogo.cn')) {
                $model->headimg = UploadService::path($headimg);
            }
        }
        if ($birthday) {
            $model->birthday = $birthday;
        }
        if ($gender) {
            $model->gender = $gender;
        }
        if ($model->save()) {
            return $this->success('保存成功');
        }
        return $this->fail('保存失败');
    }
    public function mobile(Request $request)
    {
        $D = $request->post();
        if (empty($D['mobile'])) {
            return $this->fail('请输入手机号');
        }
        if (empty($D['vcode'])) {
            return $this->fail('请输入验证码');
        }
        if (Cache::get('vcode.' . $D['mobile']) != $D['vcode']) {
            return $this->fail('验证码错误');
        }
        $MassageUser = MassageUser::where(['saas_appid' => $request->saas_appid, 'mobile' => $D['mobile']])->find();
        if ($MassageUser) {
            return $this->fail('手机号已被注册');
        }
        $MassageUser = MassageUser::where(['saas_appid' => $request->saas_appid, 'id' => $request->uid])->find();
        $MassageUser->mobile = $D['mobile'];
        if ($MassageUser->save()) {
            return $this->success('绑定成功');
        }
        return $this->fail('绑定失败');
    }
    public function password(Request $request)
    {
        $D = $request->post();
        if (empty($D['password'])) {
            return $this->fail('请输入密码');
        }
        if (empty($D['vpassword'])) {
            return $this->fail('请输入确认密码');
        }
        if ($D['password'] != $D['vpassword']) {
            return $this->fail('两次密码不一致');
        }
        $MassageUser = MassageUser::where(['saas_appid' => $request->saas_appid, 'id' => $request->uid])->find();
        $MassageUser->password = $D['password'];
        if ($MassageUser->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
    public function unBindWechat(Request $request)
    {
        $MassageUser = MassageUser::where(['saas_appid' => $request->saas_appid, 'id' => $request->uid])->find();
        if (!$MassageUser) {
            return $this->fail('用户不存在');
        }
        $MassageUserWechat = MassageUserWechat::where(['saas_appid' => $request->saas_appid, 'uid' => $request->uid])->find();
        if (!$MassageUserWechat) {
            return $this->fail('未绑定微信');
        }
        $MassageUserWechat->uid = null;
        if ($MassageUserWechat->save()) {
            return $this->success('解绑成功');
        }
        return $this->fail('解绑失败');
    }
    public function bindWechat(Request $request)
    {
        $appid = $request->appid;
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize";
        $wxappid = getHpConfig('appid', $appid, 'wx');
        if (!$wxappid) {
            return $this->fail('未配置微信公众号');
        }
        $domain = getHpConfig('domain', (int)$appid, 'plugins_domains');
        $stateObj = ['appid' => $appid, 'uid' => $request->uid, 'redirect' => 'bind'];
        $stateKey = Str::random(32);
        Cache::set($stateKey, $stateObj, 3600);
        $query = [
            'appid' => $wxappid,
            'redirect_uri' => "{$domain}/{$this->pluginPrefix}/Login/wechatBindCallback",
            'response_type' => 'code',
            'scope' => 'snsapi_userinfo',
            'state' => $stateKey,
        ];
        $url = $url . '?' . http_build_query($query) . "#wechat_redirect";
        return $this->successRes($url);
    }
    public function statictis(Request $request)
    {
        $saas_appid = $request->saas_appid;
        $uid = $request->uid;
        $data = [
            'service' => MassageCollectService::where(['saas_appid' => $saas_appid, 'uid' => $uid])->count('id'),
            'technician' => MassageCollectTechnician::where(['saas_appid' => $saas_appid, 'uid' => $uid])->count('id'),
            'unread' => 0,
            'system' => 0,
            'order_wait_start' => MassageOrdersSub::where(['saas_appid' => $saas_appid, 'uid' => $uid, 'state' => OrdersState::WAIT_START['value']])->count('id'),
            'money' => 0,
            'integral' => 0,
            'coupon_total' => MassageCouponCode::where(['saas_appid' => $saas_appid, 'uid' => $uid])->count('id'),
            'coupon_used' => MassageCouponCode::where(['saas_appid' => $saas_appid, 'uid' => $uid, 'state' => CouponCodeState::NO['value']])->count('id'),
            'coupon_unuse' => MassageCouponCode::where(['saas_appid' => $saas_appid, 'uid' => $uid, 'state' => CouponCodeState::YES['value']])->count('id'),
            'coupon_unreceive' => 0
        ];
        $MassageUserWallet = MassageUserWallet::where(['saas_appid' => $saas_appid, 'uid' => $uid])->find();
        if ($MassageUserWallet) {
            $data['money'] = $MassageUserWallet->money;
            $data['integral'] = $MassageUserWallet->integral;
        }
        return $this->successRes($data);
    }
    public function newUserGift(Request $request)
    {
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        $action=$request->get('action');
        switch($action)
        {
            case 'technician':
                $posterBg = root_path("plugin/ycMassage/public/image") . 'technician_poster.png';
                try {
                    $qrcode = $this->newTechnicianGiftQrcode($request);
                } catch (\Throwable $th) {
                    return $this->fail($th->getMessage());
                }
                $data = [
                    'poster' => $domain.'/'.$this->composePoster($request, $posterBg, $qrcode),
                    'link' => $this->getTechnicianDealerLink($request),
                ];
                break;
            default:
                $posterBg = root_path("plugin/ycMassage/public/image") . 'user_poster.png';
                try {
                    $qrcode = $this->newUserGiftQrcode($request);
                } catch (\Throwable $th) {
                    return $this->fail($th->getMessage());
                }
                $data = [
                    'poster' => $domain.'/'.$this->composePoster($request, $posterBg, $qrcode),
                    'link' => $this->getDealerLink($request),
                ];
                break;
        }
        $new_user_gift = getHpConfig('', $request->saas_appid, 'new_user_gift');
        if (isset($new_user_gift['new_user_gift_register_role'])) {
            $data['new_user_gift_register_role'] = $new_user_gift['new_user_gift_register_role'];
        }
        if (isset($new_user_gift['new_user_gift_register'])) {
            $data['new_user_gift_register'] = MassageCoupon::whereIn('id', $new_user_gift['new_user_gift_register'])->select();
        }
        if (isset($new_user_gift['new_user_gift_first_order_role'])) {
            $data['new_user_gift_first_order_role'] = $new_user_gift['new_user_gift_first_order_role'];
        }
        if (isset($new_user_gift['new_user_gift_first_order'])) {
            $data['new_user_gift_first_order'] = MassageCoupon::whereIn('id', $new_user_gift['new_user_gift_first_order'])->select();
        }
        $new_technicians_gift = getHpConfig('', $request->saas_appid, 'new_technicians_gift');
        if (isset($new_technicians_gift['new_technicians_gift_register_silver'])) {
            $data['new_technicians_gift_register_silver'] = (int)$new_technicians_gift['new_technicians_gift_register_silver'];
        }
        if (isset($new_technicians_gift['new_technicians_gift_register_gold'])) {
            $data['new_technicians_gift_register_gold'] = (int)$new_technicians_gift['new_technicians_gift_register_gold'];
        }
        if (isset($new_technicians_gift['new_technicians_gift_first_order_silver'])) {
            $data['new_technicians_gift_first_order_silver'] = (int)$new_technicians_gift['new_technicians_gift_first_order_silver'];
        }
        if (isset($new_technicians_gift['new_technicians_gift_first_order_gold'])) {
            $data['new_technicians_gift_first_order_gold'] = (int)$new_technicians_gift['new_technicians_gift_first_order_gold'];
        }
        return $this->successRes($data);
    }
    public function composePoster($request, $posterBg, $qrcode)
    {
        $action=$request->get('action');
        $image = imagecreatefrompng($posterBg);
        $width = imagesx($image);
        $height = imagesy($image);
        $system = getHpConfig('', $request->saas_appid, 'system');
        if (!empty($system['web_name'])) {
            list($r, $g, $b) = sscanf('#13374D', "#%02x%02x%02x");
            $color = imagecolorallocate($image, $r, $g, $b);
            $font = root_path("plugin/ycMassage/public/image") . 'PingFangSCMedium.ttf';
            imagettftext($image, 24, 0, 52, $height - 54, $color, $font, "立即进入 {$system['web_name']}");
            $data['web_name'] = $system['web_name'];
        }
        # 判断$qrcode是png还是jpeg
        if (Str::endsWith($qrcode, '.png')) {
            $qrcode = imagecreatefrompng($qrcode);
        } else {
            $qrcode = imagecreatefromjpeg($qrcode);
        }
        $qrcodeWidth = imagesx($qrcode);
        $qrcodeHeight = imagesy($qrcode);
        $targetSize = 150;
        $resizedOverlayImage = imagecreatetruecolor($targetSize, $targetSize);
        // 保持透明度（针对PNG图像）
        imagealphablending($resizedOverlayImage, false);
        imagesavealpha($resizedOverlayImage, true);

        // 使用 imagecopyresampled() 将叠加图片缩放到目标尺寸
        imagecopyresampled($resizedOverlayImage, $qrcode, 0, 0, 0, 0, $targetSize, $targetSize, $qrcodeWidth, $qrcodeHeight);
        imagedestroy($qrcode);

        imagecopy($image, $resizedOverlayImage, $width - $targetSize - 40, $height - $targetSize - 20, 0, 0, $targetSize, $targetSize);
        imagedestroy($resizedOverlayImage);
        # 转base64
        ob_start();
        imagepng($image);
        $image_data = ob_get_contents();
        ob_end_clean();
        imagedestroy($image);
        $imagePath="uploads/ycMassage/poster";
        $imagePublicPath=public_path($imagePath);
        if (!is_dir($imagePublicPath)) {
            mkdir($imagePublicPath, 0777, true);
        }
        $imageFile="{$request->saas_appid}_{$request->uid}_{$action}.png";
        $imageUrl = $imagePublicPath . $imageFile;
        if (file_exists($imageUrl)) {
            @unlink($imageUrl);
        }
        file_put_contents($imageUrl, $image_data);
        return $imagePath .'/'. $imageFile;
    }
    private function getDealerLink(Request $request)
    {
        $icode = urlencode(Rsa::encryptNumber($request->uid));
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        return $domain . "/app/ycMassage/#/?appid={$request->saas_appid}&icode={$icode}";
    }
    public function newUserGiftQrcode(Request $request)
    {
        $platform = $request->get('platform');
        $applet = SettingsMgr::group($request->saas_appid, 'applet');
        if ($platform == 'MP-WEIXIN' && !empty($applet['applet_appid']) && !empty($applet['applet_secret'])) {
            $mpqrcodePath = public_path("uploads/ycMassage/mpqrcode");
            $env_version = 'release';
            if (Env::get('APP_MODE') == 'dev') {
                $env_version = 'trial';
            }
            $mpqrcode = $mpqrcodePath . "{$request->saas_appid}_{$request->uid}_{$env_version}.jpeg";
            if (file_exists($mpqrcode)) {
                return $mpqrcode;
            }
            $access_token = WechatHelper::getMPAccessToken($request->saas_appid);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            $data = [
                'scene' => "puid={$request->uid}",
                'page' => 'pages/index/index',
                'check_path' => false,
                'width' => 400,
                'auto_color' => false,
                'env_version' => $env_version,
                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
            ];
            $client = new Client();
            $response = $client->post($url, ['json' => $data]);
            $result = $response->getBody()->getContents();
            if (substr($result, 0, 1) == '{') {
                $result = json_decode($result, true);
                if (isset($result['errcode'])) {
                    throw new \Exception("[{$result['errcode']}]" . $result['errmsg']);
                }
            }
            # 判断$mpqrcode目录是否存在
            if (!is_dir($mpqrcodePath)) {
                mkdir($mpqrcodePath, 0777, true);
            }
            file_put_contents($mpqrcode, $result);
            return $mpqrcode;
        }
        $builder = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($this->getDealerLink($request))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(400)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->validateResult(false);
        $result = $builder->build();
        $qrcodePath = public_path("uploads/ycMassage/qrcode");
        if (!is_dir($qrcodePath)) {
            mkdir($qrcodePath, 0777, true);
        }
        $qrcode = $qrcodePath . "{$request->saas_appid}_{$request->uid}.png";
        $result->saveToFile($qrcode);
        return $qrcode;
    }
    private function getTechnicianDealerLink(Request $request)
    {
        $icode = urlencode(Rsa::encryptNumber($request->uid));
        $domain = getHpConfig('domain', (int)$request->saas_appid, 'plugins_domains');
        return $domain . "/app/ycMassage/#/pages/technician/details?id={$request->uid}&appid={$request->saas_appid}&icode={$icode}";
    }
    public function newTechnicianGiftQrcode(Request $request)
    {
        $platform = $request->get('platform');
        $applet = SettingsMgr::group($request->saas_appid, 'applet');
        if ($platform == 'MP-WEIXIN' && !empty($applet['applet_appid']) && !empty($applet['applet_secret'])) {
            $mpqrcodePath = public_path("uploads/ycMassage/mpqrcode");
            $env_version = 'release';
            if (Env::get('APP_MODE') == 'dev') {
                $env_version = 'trial';
            }
            $mpqrcode = $mpqrcodePath . "technician_{$request->saas_appid}_{$request->uid}_{$env_version}.jpeg";
            if (file_exists($mpqrcode)) {
                return $mpqrcode;
            }
            $access_token = WechatHelper::getMPAccessToken($request->saas_appid);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}";
            $data = [
                'scene' => "puid={$request->uid}&id={$request->uid}",
                'page' => 'pages/technician/details',
                'check_path' => false,
                'width' => 400,
                'auto_color' => false,
                'env_version' => $env_version,
                'line_color' => ['r' => 0, 'g' => 0, 'b' => 0],
            ];
            $client = new Client();
            $response = $client->post($url, ['json' => $data]);
            $result = $response->getBody()->getContents();
            if (substr($result, 0, 1) == '{') {
                $result = json_decode($result, true);
                if (isset($result['errcode'])) {
                    throw new \Exception("[{$result['errcode']}]" . $result['errmsg']);
                }
            }
            # 判断$mpqrcode目录是否存在
            if (!is_dir($mpqrcodePath)) {
                mkdir($mpqrcodePath, 0777, true);
            }
            file_put_contents($mpqrcode, $result);
            return $mpqrcode;
        }
        $builder = Builder::create()
            ->writer(new PngWriter())
            ->writerOptions([])
            ->data($this->getTechnicianDealerLink($request))
            ->encoding(new Encoding('UTF-8'))
            ->errorCorrectionLevel(new ErrorCorrectionLevelHigh())
            ->size(400)
            ->margin(10)
            ->roundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->validateResult(false);
        $result = $builder->build();
        $qrcodePath = public_path("uploads/ycMassage/qrcode");
        if (!is_dir($qrcodePath)) {
            mkdir($qrcodePath, 0777, true);
        }
        $qrcode = $qrcodePath . "technician_{$request->saas_appid}_{$request->uid}.png";
        $result->saveToFile($qrcode);
        return $qrcode;
    }
}
